package com.example.apiproject.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.apiproject.dao.ArticlesLablesDao;
import com.example.apiproject.dao.UserDao;
import com.example.apiproject.entity.Articles;
import com.example.apiproject.dao.ArticlesDao;

import com.example.apiproject.entity.ArticlesLabels;
import com.example.apiproject.dao.JoinArticleDao;

import com.example.apiproject.entity.PostEntity;
import com.example.apiproject.entity.form.AddPostForm;
import com.example.apiproject.jwt.jwtutil;
import com.example.apiproject.service.ArticlesLabelsService;
import com.example.apiproject.service.ArticlesService;
import com.example.apiproject.utils.AppPageUtils;
import com.example.apiproject.utils.JsonUtils;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;




/**
 * (Articles)表服务实现类
 *
 * @author makejava
 * @since 2023-09-23 13:40:56
 */
@Service("articlesService")
public class ArticlesServiceImpl  implements ArticlesService {

    @Autowired
    private jwtutil jwtUtils;
    @Resource
    private ArticlesDao articlesDao;
    @Resource
    private ArticlesLabelsService articlesLabelsService;
    @Autowired
    private JoinArticleDao joinArticleDao;
    @Resource
    private UserDao userDao;
    @Resource
    private ArticlesLablesDao articlesLablesDao;



    /**
     * 分页查找首页帖子
     * @param num
     * @param page
     * @return
     */
    @Override
    public AppPageUtils queryPageList(Integer num,Integer page) {
        PageHelper.startPage(num,page);
        List<Articles> articles = articlesDao.queryAllByPage();
        List<PostEntity> postNewList=new ArrayList<>();
        articles.forEach(l->{
            PostEntity postEntity = new PostEntity();
            String labels = l.getLabels();
//            System.out.println("labels:"+labels);

            if (labels != null) {
                // 将逗号分隔的标签转换为列表
                List<String> labelList = Arrays.asList(labels.split(","));

                // 设置帖子的labelList为列表，用于在视图中逐个显示标签
                l.setLabelList(labelList);
            } else {
                // 如果labels字段为null，设置一个空的labelList
                l.setLabelList(new ArrayList<>());
            }
//            postEntity.setCreateTime(l.getCreateTime());
            BeanUtils.copyProperties(l,postEntity,new String[]{"startTime"});
            postEntity.setStartTime(l.getStartTime());
            postEntity.setCreateTime(l.getCreateTime());
            postEntity.setImages(JsonUtils.JsonToList(l.getImages()));
            postEntity.setNickName(userDao.queryNameById(l.getUserId()));
            postEntity.setAvater(userDao.queryAvatarById(l.getUserId()));
            postNewList.add(postEntity);
        });
        long count = articlesDao.count(null);
        AppPageUtils appPage=new AppPageUtils(postNewList,(int)count,page,num);

        return appPage;
    }

    /**
     * 通过label模糊查询
     * @param num
     * @param page
     * @param label
     * @return
     */
    @Override
    public AppPageUtils queryByLabel(Integer num, Integer page, String label) {
        PageHelper.startPage(num,page);
        List<Articles> articles = articlesDao.queryByLabel(label);
        List<PostEntity> postNewList=new ArrayList<>();
        articles.forEach(l->{
            PostEntity postEntity = new PostEntity();
            String labels = l.getLabels();
//            System.out.println("labels:"+labels);

            if (labels != null) {
                // 将逗号分隔的标签转换为列表
                List<String> labelList = Arrays.asList(labels.split(","));

                // 设置帖子的labelList为列表，用于在视图中逐个显示标签
                l.setLabelList(labelList);
            } else {
                // 如果labels字段为null，设置一个空的labelList
                l.setLabelList(new ArrayList<>());
            }
//            postEntity.setCreateTime(l.getCreateTime());
            BeanUtils.copyProperties(l,postEntity,new String[]{"startTime"});
            postEntity.setStartTime(l.getStartTime());
            postEntity.setCreateTime(l.getCreateTime());
            postEntity.setImages(JsonUtils.JsonToList(l.getImages()));
            postEntity.setNickName(userDao.queryNameById(l.getUserId()));
            postEntity.setAvater(userDao.queryAvatarById(l.getUserId()));
            postNewList.add(postEntity);
        });
        long count = articlesDao.countLabel(label);
        AppPageUtils appPage=new AppPageUtils(postNewList,(int)count,page,num);

        return appPage;
    }




    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Articles queryById(String id) {
        Articles article = articlesDao.queryById(id);

        if (article != null) {
            // 获取帖子的labels
            String labels = article.getLabels();
            System.out.println("labels:"+labels);

            if (labels != null) {
                // 将逗号分隔的标签转换为列表
                List<String> labelList = Arrays.asList(labels.split(","));

                // 设置帖子的labelList为列表，用于在视图中逐个显示标签
                article.setLabelList(labelList);
            } else {
                // 如果labels字段为null，设置一个空的labelList
                article.setLabelList(new ArrayList<>());
            }
        }

        return article;
    }



    /**
     * 分页查询
     *
     * @param articles 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<Articles> queryByPage(Articles articles, PageRequest pageRequest) {
        long total = this.articlesDao.count(articles);
        return new PageImpl<>(this.articlesDao.queryAllByLimit(articles, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param articles 实例对象
     * @return 实例对象
     */
    @Override

    @Transactional(rollbackFor = Exception.class)
    public int insert(AddPostForm articles, HttpServletRequest request) {
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }
        System.out.println(token);
        int  useId = jwtUtils.getUserId(token);

//       显示已有标签供用户选择
        List<ArticlesLabels> articlesLabels = articlesLablesDao.queryAllLabels();
        for (ArticlesLabels articlesLabel : articlesLabels){
            List<String> labelsName = new ArrayList<>();
            labelsName.add(articlesLabel.getLabel());
        }

//      新增设置帖子标签
        String labels = articles.getLabels();
        String[] labelArray = labels.split(",");
        StringBuilder labelIdBuilder = new StringBuilder();
        for (String label : labelArray) {
            ArticlesLabels existingLabel = articlesLabelsService.getLabelByContent(label);
            if (existingLabel == null) {
                ArticlesLabels newLabel = new ArticlesLabels();
                newLabel.setLabel(label);
                newLabel.setNum(1);
                articlesLabelsService.addLabel(newLabel);
                labelIdBuilder.append(newLabel.getId()).append(",");
            } else {
                existingLabel.setNum(existingLabel.getNum() + 1);
                articlesLabelsService.updateLabelNum(existingLabel);
                labelIdBuilder.append(existingLabel.getId()).append(",");
            }
        }
//      分界线

        Articles art = new Articles();
        art.setUserId(useId);
        art.setTitle(articles.getTitle());
        art.setContent(articles.getContent());
        List<String> l=articles.getMedia();

        art.setImages(JSON.toJSONString(l));
        art.setNumber(articles.getIndex()+1);
        if(articles.getStartTime()!=null) {
            art.setStartTime(articles.getStartTime());
        }
        art.setCreateTime(LocalDateTime.now());
        if(articles.getAddress()!=null) {
            art.setLocation(articles.getAddress());
        }
        art.setLabelIds(articles.getCateName());

        art.setLabels(articles.getLabels());
        art.setLabelId(labelIdBuilder.toString());
//        articlesDao.insertArticle(article);
        UUID uuid = UUID.randomUUID();
        art.setId(uuid.toString());
        int id = articlesDao.insert(art);
        return id;
    }
//    测试添加帖子标签
//    @Override
//    public void addArticle(Articles article) {
//        String[] labelArray = article.getLabels().split(",");
//        StringBuilder labelIdBuilder = new StringBuilder();
//        for (String label : labelArray) {
//            ArticlesLabels existingLabel = articlesLabelsService.getLabelByContent(label);
//            if (existingLabel == null) {
//                ArticlesLabels newLabel = new ArticlesLabels();
//                newLabel.setLabel(label);
//                newLabel.setNum(1);
//                articlesLabelsService.addLabel(newLabel);
//                labelIdBuilder.append(newLabel.getId()).append(",");
//            } else {
//                existingLabel.setNum(existingLabel.getNum() + 1);
//                articlesLabelsService.updateLabelNum(existingLabel);
//                labelIdBuilder.append(existingLabel.getId()).append(",");
//            }
//        }
//
//        article.setLabelId(labelIdBuilder.toString());
//        articlesDao.insertArticle(article);
//    }

    @Override
    public Integer update(Articles articles) {


        return   articlesDao.update(articles);
    }

    /**
//     * 修改数据
//     *
//     * @param articles 实例对象
//     * @return 实例对象
//     */
//    @Override
//    public Articles update(Articles articles) {
//        this.articlesDao.update(articles);
//        return this.queryById(articles.getId());
//    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.articlesDao.deleteById(id) > 0;
    }

    /**
     * 按照类型展示帖子
     * @param pageNum
     * @param pageSize
     * @param type
     * @return
     */
    @Override
    public AppPageUtils queryPageListBytype(Integer pageNum, Integer pageSize, String type) {
        PageHelper.startPage(pageNum,pageSize);
        List<Articles> articles = articlesDao.queryAllBytype(type);
        List<PostEntity> postNewList=new ArrayList<>();
        articles.forEach(l->{
            PostEntity postEntity = new PostEntity();
            BeanUtils.copyProperties(l,postEntity);
            postEntity.setCreateTime(l.getCreateTime());
            postEntity.setImages(JsonUtils.JsonToList(l.getImages()));
            postEntity.setNickName(userDao.queryNameById(l.getUserId()));
            postEntity.setAvater(userDao.queryAvatarById(l.getUserId()));
            postNewList.add(postEntity);
        });
        Articles art=new Articles();
        art.setLabelIds(type);
        long count = articlesDao.count(art);
        AppPageUtils appPage=new AppPageUtils(postNewList,(int)count,pageSize,pageNum);

        return appPage;
    }

    /**
     * 根查询当前用户Id的寻搭文章
     * @param request
     * @return 文章集合1
     */
    @Override
    public AppPageUtils queryByUserId(HttpServletRequest request,  Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }
        int  userId = jwtUtils.getUserId(token);
        Articles art=new Articles();
        art.setUserId(userId);
        List<Articles> list = articlesDao.queryByUserId(art);
        List<PostEntity> postNewList=new ArrayList<>();
//        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        list.forEach(l->{
            PostEntity postEntity = new PostEntity();

            BeanUtils.copyProperties(l,postEntity);
            postEntity.setTitle(l.getTitle());
            postEntity.setCreateTime(l.getCreateTime());

            postEntity.setStartTime(l.getStartTime());
            postEntity.setImages(JsonUtils.JsonToList(l.getImages()));
            postEntity.setNickName(userDao.queryNameById(l.getUserId()));
            postEntity.setAvater(userDao.queryAvatarById(l.getUserId()));
            postNewList.add(postEntity);
        });
        Articles articles=new Articles();
        articles.setUserId(userId);
        long count = articlesDao.count(articles);
        AppPageUtils appPage=new AppPageUtils(postNewList,(int)count,pageSize,pageNum);

        return appPage;

    }

    @Override
    public List<PostEntity> queryRecent(HttpServletRequest request) {

        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }
        int  userId = jwtUtils.getUserId(token);
        List<String> ids = joinArticleDao.queryArtIdByUserId(userId);

        List<Articles> list =new ArrayList<>();
        if(ids.size()==0){  list =articlesDao.queryRecentnull(userId,LocalDateTime.now());}
        else {
             list = articlesDao.queryRecent(userId, LocalDateTime.now(), ids);
        }

//        System.out.println(ids);
//        List<Articles> list =articlesDao.queryRecent(userId,LocalDateTime.now(),ids);

        List<PostEntity> postNewList=new ArrayList<>();
        list.forEach(l->{
            PostEntity postEntity = new PostEntity();
            BeanUtils.copyProperties(l,postEntity);
            postEntity.setCreateTime(l.getCreateTime());
            postEntity.setImages(JsonUtils.JsonToList(l.getImages()));

            postEntity.setStartTime(l.getStartTime());
            postEntity.setNickName(userDao.queryNameById(l.getUserId()));
            postEntity.setAvater(userDao.queryAvatarById(l.getUserId()));
            postNewList.add(postEntity);
        });

        return postNewList;
    }
}
